import React, { useState, useEffect } from "react";
import axios from "axios";
import './Newspage.css';
import Navbar from './Navbar';
function NewsPagination() {
  const [news, setNews] = useState([]);
  const [page, setPage] = useState(1);
  const [totalPages, setTotalPages] = useState(0);

  // 获取分页新闻
  const fetchNews = async (page) => {
    try {
      const response = await axios.get(`http://localhost:8080/news/page?page=${page}&limit=10`, {
        headers: {
          'Authorization':  localStorage.getItem('token'),  // 示例：添加 Bearer token 作为认证头部
          'Content-Type': 'application/json',        // 添加 Content-Type 头部（如果需要的话）
        }
      });
      console.log("返回值："+response.data.data.content);
      setNews(response.data.data.content);
      // 假设接口返回总数据量，计算总页数
      setTotalPages(Math.ceil(20000 / 10)); // 2万条新闻，每页10条
    } catch (error) {
      console.error("加载新闻失败", error);
    }
  };

  useEffect(() => {
    fetchNews(page);
  }, [page]);

  return (
    <div>
      <Navbar />
    <div className="news-container">
  <h2 className="title">新闻列表</h2>
  <ul className="news-list">
    {news.map((item, index) => (
      <div className="news-item" key={index}>
        <li className="news-title">{item.title}</li> {/* 假设新闻数据包含 title 字段 */}
        <p className="news-content">{item.content}</p>
      </div>
    ))}
  </ul>

  <div className="pagination">
    <button
      onClick={() => setPage((prev) => Math.max(prev - 1, 1))}
      disabled={page === 1}
      className="pagination-btn"
    >
      上一页
    </button>
    <span className="page-info">第 {page} 页</span>
    <button
      onClick={() => setPage((prev) => Math.min(prev + 1, totalPages))}
      disabled={page === totalPages}
      className="pagination-btn"
    >
      下一页
    </button>
  </div>
</div>
</div>
  );
}

export default NewsPagination;